﻿using STHPMS1.BLL.B_Core;
using STHPMS1.ICore.I_BLL.Bus;
using STHPMS1.ICore.I_Entity.Info;
using STHPMS1.ICore.I_Entity.Stmpms1;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using STHPMS1.Common.C_Entity.Stmpms1;
using STHPMS1.ICore;
using STHPMS1.ICore.I_Serv;
using EmitMapper;
using STHPMS1.Common.C_Enum;
using System.Collections;
using STHPMS1.Common.C_Extension;
using System.Data;
using Newtonsoft.Json.Linq;
using STHPMS1.ICore.I_DAL;
using System.Linq;

namespace STHPMS1.BLL.B_Bus
{
    public class B_PmstcBus : BllBase, IB_PmstcBill
    {
        public void Save<T>(T entity)
            where T : class ,IB_Pmstc
        {
            if (entity.Rdwayid == null) throw new Exception("路线编号不能为空!");
            if (entity.Direction_Dictid ==0) throw new Exception("行车方向不能为空!");
            if (entity.Pvmttype_Dictid == 0) throw new Exception("面层类型不能为空!");
            if (entity.Endmp <= entity.Beginmp) throw new Exception("终点桩号要大于起点桩号!");
            if (this.Scene.Dal.Sthpms1.Exists<B_Roadway>(p =>(entity.Beginmp < p.Beginmp || entity.Endmp > p.Endmp) &&
                                                               p.Rdwayid == entity.Rdwayid))
            {
                throw new Exception("桩号不在该路线的桩号范围!");
            }
            if (this.Scene.Dal.Sthpms1.Exists<B_Pmstc>(p => (p.Rdwayid == entity.Rdwayid && 
                                                                        p.Direction_Dictid==entity.Direction_Dictid ) &&
                                                                      (p.Beginmp < entity.Beginmp &&
                                                                       p.Endmp > entity.Beginmp) &&
                                                                       p.Struid!=entity.Struid))
            {
                throw new Exception("起点桩号在路线中某个路面结构中已经存在!");
            }
            if (this.Scene.Dal.Sthpms1.Exists<B_Pmstc>(p => (p.Rdwayid == entity.Rdwayid &&
                                                                        p.Direction_Dictid == entity.Direction_Dictid) &&
                                                                         (p.Beginmp < entity.Endmp &&
                                                                          p.Endmp > entity.Endmp) &&
                                                                        p.Struid != entity.Struid))
            {
                throw new Exception("终点桩号在路线中某个路面结构中已经存在!");
            }
            if (this.Scene.Dal.Sthpms1.Exists<B_Pmstc>(p => (p.Rdwayid == entity.Rdwayid &&
                                                                        p.Direction_Dictid == entity.Direction_Dictid) &&
                                                                        (p.Beginmp > entity.Beginmp &&
                                                                         p.Endmp < entity.Endmp) &&
                                                                        p.Struid != entity.Struid))
            {
                throw new Exception("此桩号在路线中已经存在路面结构!");
            }

            if (string.IsNullOrEmpty(entity.Struid))
                entity.Struid = MyApp.Locator.GetInstance<IKeyGenrateService>().NewPmstcId(entity);

            entity.His_Version = this.Scene.Bll.B_Roadway.GetNewHistoryVersion(entity.Rdwayid);
            entity.Importdate = DateTime.Now;

            this.Scene.Dal.Sthpms1.Save(entity);
        }

        public void Remove(IB_Pmstc entity)
        {
            ISthpms1Dao dao = this.Scene.Dal.Sthpms1;
            using (IDbTransaction dbTrans = dao.BeginTransaction())
            {
                B_Pmstc_History history = ObjectMapperManager.DefaultInstance.GetMapper<IB_Pmstc, B_Pmstc_History>().Map(entity);
                if (history != null)
                {
                    history.Importdate = DateTime.Now;
                    dao.Save(history);
                }

                List<B_Layer_History> layers = new List<B_Layer_History>();
                foreach (var item in dao.Select<B_Layer>(p => p.Struid == entity.Struid))
                {
                    B_Layer_History layer = ObjectMapperManager.DefaultInstance.GetMapper<IB_Layer, B_Layer_History>().Map(item);
                    if (layer != null)
                    {
                        layer.Importdate = DateTime.Now;
                        dao.Save(layer);
                    }

                }

                dao.DeleteById<B_Pmstc>(entity.Struid);
                dao.Delete<B_Layer>(p => p.Struid == entity.Struid);
                dbTrans.Commit();
            }

        }

        public IEnumerable<T> Get<T>(Expression<Func<T, bool>> predicate, IPagingInfo info)
            where T : class, IB_Pmstc
        {
            return this.Scene.Dal.Sthpms1.Select<T>(predicate, info, k => k.Importdate, true);
        }

        public IEnumerable<T> Get<T>(string RDWAYID, float BEGINMP, float ENDMP) where T : class,IB_Pmstc
        {
            return this.Scene.Dal.Sthpms1.Select<T>(q => q.Rdwayid == RDWAYID && q.Beginmp <= BEGINMP && q.Endmp >= ENDMP, null);
        }

        public IEnumerable<T> GetPmstc<T>(string RDWAYID) where T : class,IB_Pmstc
        {
            return this.Scene.Dal.Sthpms1.Select<T>(q => q.Rdwayid == RDWAYID, null);
        }

        /// <summary>
        /// 返回设计弯沉
        /// </summary>
        /// <param name="start">起始桩号</param>
        /// <param name="end">结束桩号</param>
        /// <param name="rdid">路线编号</param>
        /// <returns></returns>
        public string GetDEGDF(double start, double end,string rdid)
        {
            return this.Scene.Bll.B_Pmstc.GetDEGDF(start, end, rdid);
        }


        public ArrayList GetLayers(string struid=null)
        {
            var data = new ArrayList();
            List<B_Layer> layers=this.Scene.Dal.Sthpms1.Select<B_Layer>(p=>p.Struid==struid);

            foreach (var value in Enum.GetValues(typeof(LayerEnum)))
            {
                B_Layer layer = layers.FirstOrDefault<B_Layer>(p => p.Layer_Dictid == (int)value);
                LayerEnum layerEnum = (LayerEnum)value;
                dynamic obj1 = new System.Dynamic.ExpandoObject();
                if (layer == null)
                {
                    obj1.status = "未使用";
                    obj1.Layid = null;
                    obj1.Struid = struid;
                    obj1.Layer_name = layerEnum.GetEnumDescription();
                    obj1.Layer_dictid = value;
                    obj1.Stru_Id = null;
                    obj1.Thick = null;
                    obj1.Poirat = null;
                    obj1.Elamod = null;
                    obj1.Layercoeff = null;
                    obj1.Draincoeff = null;
                }
                else
                {
                    obj1.status = "已使用";
                    obj1.Layid = layer.Layid;
                    obj1.Struid = struid;
                    obj1.Layer_name = layerEnum.GetEnumDescription();
                    obj1.Layer_dictid = value;
                    obj1.Stru_Id = layer.Stru_Id;
                    obj1.Thick = layer.Thick;
                    obj1.Poirat = layer.Poirat;
                    obj1.Elamod = layer.Elamod;
                    obj1.Layercoeff = layer.Layercoeff;
                    obj1.Draincoeff = layer.Draincoeff;
                }
              
                data.Add(obj1);
            }

            return data;
        }


        public DataTable GetLayerMate(int lay)
        { 
            string data="";
            switch((LayerEnum)lay)
            {
                case LayerEnum.L30:
                {
                    data = "'AC-5','AC-10','AC-13','AC-16','改性AC-10','改性AC-13','改性AC-16','sup-13','SMA-13','SMA-16','OGFC-13','OGFC-16','AM-16','AM-20','AM-25','AM-35','ARAC-13','ARAC-20','ARAC-25','沥青贯入式','沥青表处','水泥混凝土板'";
                    break;
                }
                case LayerEnum.L45:
                {
                    data = "'AC-13','AC-16', 'AC-20','改性AC-13','改性AC-16','改性AC-20', 'sup-19','sup-25','AM-16','AM-20','AM-25','AM-35','水泥混凝土板'";
                    
                    break;
                }
                case LayerEnum.L50:
                {
                    data = "'AC-16','AC-20','AC-25','sup-25','改性AC-16','改性AC-20','改性AC-25','AM-16','AM-20','AM-25','AM-35','ATPB-25','ATPB-30','ATB-25','ATB-30','ATB-35','LSM-30','LSM-35'";
                    break;
                }
                case LayerEnum.L55:
                {
                    data = "'水泥稳定碎石','水泥稳定砂砾','水泥稳定土','石灰稳定碎石','石灰稳定砂砾','石灰土','二灰碎石','二灰砂砾','二灰土','石灰工业废渣稳定碎石','石灰工业废渣稳定砂砾','石灰工业废渣稳定土','ATPB-25','ATPB-30','ATB-25','ATB-30','ATB-35','LSM-30','LSM-35','AM-16','AM-20','AM-25','级配砾石','级配碎石','天然砂砾','级配碎砾石','泥结碎石','泥灰结碎石','填隙碎石','贫混凝土'";
                    break;
                }
                case LayerEnum.L75:
                {
                    data = "'水泥稳定碎石','水泥稳定砂砾','水泥稳定土','石灰稳定碎石','石灰稳定砂砾','石灰土','二灰碎石','二灰砂砾','二灰土','石灰工业废渣稳定碎石','石灰工业废渣稳定砂砾','石灰工业废渣稳定土','ATPB-25','ATPB-30','ATB-25','ATB-30','LSM-30','LSM-35','AM-16','AM-20','AM-25','LSM-30','LSM-35','级配砾石','级配碎石','天然砂砾','级配碎砾石','泥结碎石','泥灰结碎石','填隙碎石','贫混凝土'";
                    break;
                }
                case LayerEnum.L95:
                {
                    data="'级配砾石','级配碎石','天然砂砾','级配碎砾石','泥结碎石','泥灰结碎石','填隙碎石'";
                    break;
                }
            }

            return this.Scene.Dal.Sthpms1.B_Pmstc.GetStruMates(data);

        }

        public double SaveLayInStruct(string rdwayid,int direction_Dictid,string struid,string data)
        {
            double thick_all =0;
            if (string.IsNullOrEmpty(struid)) throw new Exception("路面结构编号不存在");
            if (string.IsNullOrEmpty(data)) throw new Exception("更新的层数据为空");
            List<B_Layer> layers = new List<B_Layer>();
            JArray obj = JArray.Parse(data);
            if (obj == null) return thick_all;

            double thick_lay = 0;
            int count_lay = 0;
            int count_bas = 0;
            foreach (JObject  item in obj.Children())
            {
                if(item["status"].Value<string>()=="未使用")continue;
                B_Layer layer = new B_Layer();
                layer.Rdwayid = rdwayid;
                layer.Direction_Dictid = direction_Dictid;

                if (!string.IsNullOrEmpty(item["Struid"].Value<string>()))
                    layer.Struid = item["Struid"].Value<string>();
                else
                    throw new Exception("路面结构编号不能为空!");

                if (!string.IsNullOrEmpty(item["Layer_dictid"].Value<string>()))
                    layer.Layer_Dictid = item["Layer_dictid"].Value<int>();
                else
                    throw new Exception("层位不能为空!");


                if (layer.Layer_Dictid == LayerEnum.L100.GetEnumValue())
                {
                    layer.Thick = null;
                }
                else
                {
                    if (!string.IsNullOrEmpty(item["Thick"].Value<string>()))
                        layer.Thick = item["Thick"].Value<double>();
                    else
                        throw new Exception("厚度不能为空!");                
                }
                
                if (!string.IsNullOrEmpty(item["Stru_Id"].Value<string>()))
                    layer.Stru_Id = item["Stru_Id"].Value<string>();

                if (!string.IsNullOrEmpty(item["Poirat"].Value<string>()))
                    layer.Poirat = item["Poirat"].Value<double>();
                if (!string.IsNullOrEmpty(item["Elamod"].Value<string>()))
                    layer.Elamod = item["Elamod"].Value<double>();
                else
                    throw new Exception("回弹模量不能为空!");

                if (!string.IsNullOrEmpty(item["Layercoeff"].Value<string>()))
                    layer.Layercoeff = item["Layercoeff"].Value<double>();
                if (!string.IsNullOrEmpty(item["Draincoeff"].Value<string>()))
                    layer.Draincoeff = item["Draincoeff"].Value<double>();

                if (LayerEnum.L30.GetEnumValue() == layer.Layer_Dictid ||
                    LayerEnum.L45.GetEnumValue() == layer.Layer_Dictid ||
                    LayerEnum.L50.GetEnumValue() == layer.Layer_Dictid)
                {
                    count_lay++;
                    thick_lay += layer.Thick.ToD();
                }


                if (LayerEnum.L55.GetEnumValue() == layer.Layer_Dictid ||
                    LayerEnum.L75.GetEnumValue() == layer.Layer_Dictid) count_bas++;

                layer.Layid = MyApp.Locator.GetInstance<IKeyGenrateService>().NewLayId(layer.Struid, layer.Layer_Dictid.ToString());
                layer.Importdate = DateTime.Now;
                layer.His_Version = this.Scene.Bll.B_Roadway.GetNewHistoryVersion(rdwayid);
                layers.Add(layer);

                thick_all += layer.Thick??0;
            }

            if (count_lay == 0) throw new Exception("需要填写至少一项面层数据!");
            if (count_bas == 0) throw new Exception("需要填写至少一项基层数据!");

            ISthpms1Dao dao = this.Scene.Dal.Sthpms1;
            using (IDbTransaction dbTrans = dao.BeginTransaction())
            {
                dao.Delete<B_Layer>(p => p.Struid == struid);
                if (layers.Count > 0)dao.SaveAll(layers);
                dao.Update<B_Pmstc>(new { THICK_T = thick_all, THICK_S=thick_lay }, p => p.Struid == struid);

                dbTrans.Commit();
            }
            return thick_all;
        }


        public DataTable GetEmptyData()
        {
            return this.Scene.Dal.Sthpms1.B_Pmstc.GetEmptyData();
        }

        public DataTable GetLayerEmptyData()
        {
            return this.Scene.Dal.Sthpms1.B_Pmstc.GetLayerEmptyData();
        }

        public List<T> SearchByStruId<T>(string stru_id) where T : class, IB_Stru_Mate
        {
            ISthpms1Dao dao = this.Scene.Dal.Sthpms1;
            return dao.Select<T>(q => q.Stru_Id == stru_id);
        }

      
    }
}
